package com.caijb.juc;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author caijb
 * @version 1.0
 * @data 2025/10/31 01:24
 */
public class ExchangerDemo {
    private static final Exchanger<String> exchanger = new Exchanger<>();

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        // 线程A
        executor.submit(() -> {
            try {
                String data = "线程A的数据";
                System.out.println("线程A准备交换数据: " + data);

                // 交换数据
                String receivedData = exchanger.exchange(data);
                System.out.println("线程A收到数据: " + receivedData);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        executor.submit(() -> {
            try {
                String data = "线程C的数据";
                System.out.println("线程C准备交换数据: " + data);

                // 交换数据
                String receivedData = exchanger.exchange(data);
                System.out.println("线程C收到数据: " + receivedData);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        executor.submit(() -> {
            try {
                String data = "线程D的数据";
                System.out.println("线程D准备交换数据: " + data);

                // 交换数据
                String receivedData = exchanger.exchange(data);
                System.out.println("线程D收到数据: " + receivedData);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        // 线程B
        executor.submit(() -> {
            try {
                String data = "线程B的数据";
                System.out.println("线程B准备交换数据: " + data);

                // 交换数据
                String receivedData = exchanger.exchange(data);
                System.out.println("线程B收到数据: " + receivedData);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        executor.shutdown();
    }
}
